package com.dwork.base.exception;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.dwork.base.controller.BaseController;
import com.dwork.base.controller.utils.JsonUtil;



@Component
public class SpringExceptionHandler implements HandlerExceptionResolver{
	private static Logger logger = LoggerFactory.getLogger(SpringExceptionHandler.class);
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		String accept = request.getHeader("Accept");
		if(Pattern.matches(".*json.*", accept)){
			
			Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put(BaseController.STATUS, BaseController.STATUS_FAILURE);
            responseMap.put(BaseController.MESSAGE, (ex.getMessage()==null || "".equals(ex.getMessage())?"系统异常，请稍后重试！":ex.getMessage()));
            try {
            	response.setContentType("application/json;charset=UTF-8");
            	response.setCharacterEncoding("UTF-8");
            	response.getWriter().print(JsonUtil.toJson(responseMap));
            	response.getWriter().flush();
            	response.getWriter().close();
    		} catch (Exception e) {
    			logger.info(String.format("系统未处理的错误:{%s}", e.getMessage()));
    		}
            return null;
            
		}else{
			ModelAndView mv = new ModelAndView("redirect:/error/500");
			RedirectAttributesModelMap model = new RedirectAttributesModelMap();
			if(ex instanceof DworkException){
				model.addAttribute(BaseController.MESSAGE, ex.getMessage());
				model.addAttribute(BaseController.STATUS, ((DworkException) ex).getCode());
			}else{
				mv.addObject(BaseController.MESSAGE, "系统异常，请稍后重试！");
				mv.addObject(BaseController.STATUS,"500" );
			}
			return mv;	
		}
	}
  

}
